package main

import (
	"gokitpractice/middleware"
	"net/http"
	"os"

	"github.com/go-kit/log"
	"github.com/go-kit/log/level"
	"github.com/gorilla/mux"

	"github.com/go-kit/kit/metrics/prometheus"
	httptransport "github.com/go-kit/kit/transport/http"
	stdprometheus "github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
	logger := log.NewLogfmtLogger(os.Stderr)
	reqcount := prometheus.NewCounterFrom(stdprometheus.CounterOpts{
		Namespace: "go_ms_test",
		Subsystem: "api",
		Name:      "request_count",
		Help:      "Total request count",
	}, []string{})
	dur := prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{
		Namespace: "go_ms_test",
		Subsystem: "api",
		Name:      "request_duration",
		Help:      "request duration",
	}, []string{})

	db := GetDBConn()

	r := mux.NewRouter()

	var svc AccountService
	svc = accountservice{}

	{
		repository, err := NewRepo(db, logger)
		if err != nil {
			level.Error(logger).Log("exit", err)
			os.Exit(-1)
		}
		svc = NewService(repository, logger)
	}

	//create handlers
	CreateAccountHandler := httptransport.NewServer(
		middleware.PromeMetricsMiddleware(logger, reqcount, dur)(makeCreateCustomerEndpoint(svc)),
		decodeCreateCustomerRequest,
		encodeResponse,
	)
	GetByCustomerIdHandler := httptransport.NewServer(
		middleware.PromeMetricsMiddleware(logger, reqcount, dur)(makeGetCustomerByIdEndpoint(svc)),
		decodeGetCustomerByIdRequest,
		encodeResponse,
	)
	GetAllCustomersHandler := httptransport.NewServer(
		middleware.PromeMetricsMiddleware(logger, reqcount, dur)(makeGetAllCustomersEndpoint(svc)),
		decodeGetAllCustomersRequest,
		encodeResponse,
	)
	DeleteCustomerHandler := httptransport.NewServer(
		middleware.PromeMetricsMiddleware(logger, reqcount, dur)(makeDeleteCustomerEndpoint(svc)),
		decodeDeleteCustomerRequest,
		encodeResponse,
	)
	UpdateCustomerHandler := httptransport.NewServer(
		middleware.PromeMetricsMiddleware(logger, reqcount, dur)(makeUpdateCustomerEndpoint(svc)),
		decodeUpdateCustomerRequest,
		encodeResponse,
	)

	http.Handle("/", r)
	http.Handle("/account", CreateAccountHandler)
	http.Handle("/account/update", UpdateCustomerHandler)
	http.Handle("/metrics", promhttp.Handler())

	r.Handle("/account/getAll", GetAllCustomersHandler).Methods("GET")
	r.Handle("/account/{customerid}", GetByCustomerIdHandler).Methods("GET")
	r.Handle("/account/{customerid}", DeleteCustomerHandler).Methods("DELETE")

	logger.Log("Msg", "HTTP", "addr", ":8000")
	logger.Log("err", http.ListenAndServe(":8000", nil))

}
